﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using CloudApiServer.Services;
using Google.Protobuf.WellKnownTypes;
using log4net;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Asn1.X509;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static log4net.Appender.RollingFileAppender;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 浙江省异地就医接口控制器
    /// </summary>
    [RoutePrefix("srs/cts-int/api")]
    public class FsiApiZheJiangCtsApiController : ApiController
    {
        private readonly YbSettlementStmtService _ybSettlementStmtService;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FsiApiZheJiangCtsApiController()
        {
            _ybSettlementStmtService =new YbSettlementStmtService();
        }
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江医保异地自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string infno = fsiRequest.infno;
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江医保异地自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江医保异地自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江医保异地自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 1502异地对总帐
        /// </summary>
        /// <returns></returns>
        [Route("transBegin/medicine")]
        [HttpPost]
        public async Task<IHttpActionResult> TransBeginMedicine(HttpRequestMessage request)
        {

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                DataTable dtpsninfo = new DataTable();
                string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<object>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    if (fsiRequest.infno=="1505")
                    {
                        var fsiReques1505 = JsonConvert.DeserializeObject<FsiRequestHeader<InputTransBeginMedicine1505>>(request.Content.ReadAsStringAsync().Result);
                        var (output,warn_msg) = await _ybSettlementStmtService.CrossRegionStmtTotal(fsiReques1505, this.GetType().Name);
                        var FsiHeader = new FsiHeader<OutputTransBeginMedicine1505>
                        {
                            output = output,
                            infcode = 0,
                            warn_msg = warn_msg,
                            cainfo = null,
                            err_msg = "success",
                            refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            signtype = null,
                            respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                        };
                        return Json(FsiHeader);
                    }
                    else if (fsiRequest.infno == "1812")
                    {
                        var fsiReques1812 = JsonConvert.DeserializeObject<FsiRequestHeader<InputTransBeginMedicine1812>>(request.Content.ReadAsStringAsync().Result);
                        var output = await _ybSettlementStmtService.CrossRegionStmtUnfinishedDetails(fsiReques1812, this.GetType().Name);
                        var FsiHeader = new FsiHeader<OutputTransBeginMedicine1812>
                        {
                            output = output,
                            infcode = 0,
                            warn_msg =  null,
                            cainfo = null,
                            err_msg = "success",
                            refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            signtype = null,
                            respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                            inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                        };
                        return Json(FsiHeader);
                    }
                    else
                    {
                        throw new Exception($"异地对账接口参数校验失败：传入的接口编号【{fsiRequest.infno}】未被定义！当前入参:{request.Content.ReadAsStringAsync().Result}");
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江医保异地自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江医保异地自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
    }
}
